<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 提示 -->
      <el-alert
        title="注意：只允许为三级分类设置相关参数！"
        type="warning"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类 -->
      <el-row class="avt_out">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selecdcateKeys"
            :options="catelist"
            expand-trigger="hover"
            :props="cateprops"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs标签页 -->
      <el-tabs v-model="activeName" @tab-click="slesecatehandleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isberverid"
            @click="addterdialogVisible = true"
            >添加参数</el-button
          >
          <el-table :data="manyTabdata" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  closable
                  :key="i"
                  @close="handleClose(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入文本框和按钮的切换 -->
                <!-- 在数据中定义独自的inputVisible和inputValue-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible" 
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >

                <!--  -->
              </template>
            </el-table-column>

            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  size="mini"
                  @click="showEditDig(scope.row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="showdelete(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isberverid"
            @click="addterdialogVisible = true"
            >添加属性</el-button
          >
          <el-table :data="onlyTabdata" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope"> 
                  <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  closable
                  :key="i"
                  @close="handleClose(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入文本框和按钮的切换 -->
                <!-- 在数据中定义独自的inputVisible和inputValue-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible" 
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >

              </template>
            </el-table-column>

            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  size="mini"
                  @click="showEditDig(scope.row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="showdelete(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加对话框 -->
    <el-dialog
      :title="this.activeName === 'many' ? '添加动态参数' : '添加静态属性'"
      :visible.sync="addterdialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        label-width="100px"
        :model="addform"
        :rules="addformrules"
        ref="addformref"
      >
        <el-form-item
          :label="this.activeName === 'many' ? '动态参数：' : '静态属性：'"
          prop="attr_name"
        >
          <el-input v-model="addform.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addterdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addparams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改分类的对话框 -->
    <el-dialog
      :title="this.activeName === 'many' ? '修改动态参数' : '修改静态属性'"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        label-width="100px"
        :model="editform"
        :rules="editformrules"
        ref="editformref"
      >
        <el-form-item
          :label="this.activeName === 'many' ? '动态参数：' : '静态属性：'"
          prop="attr_name"
        >
          <el-input v-model="editform.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editparams('editform')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import uri from "../../config/uri";
export default {
  data() {
    return {
      // 获取商品分类的数据
      catelist: [],
      // 级联选择器props的配置
      cateprops: {
        // 指定选中的值
        value: "cat_id",
        // 指定看到的值
        label: "cat_name",
        // 父子嵌套的属性
        children: "children",
      },
      // 级联选择器v-model
      selecdcateKeys: [],
      // tabs标签v-model，默认
      activeName: "many",
      // 存放动态参数数据
      manyTabdata: [],
      // 存放静态属性的数据
      onlyTabdata: [],
      // 添加对话框的显示与否
      addterdialogVisible: false,
      // 定义添加对话框form表单的model
      addform: {
        attr_name: "",
      },
      // 添加表单的验证规则
      addformrules: {
        attr_name: [
          {
            required: true,
            message: "请输入参数",
            trigger: "blur",
          },
        ],
      },
      //修改对话框的显示与否
      editdialogVisible: false,
      // 修改对话框的form表单model
      editform: [],
      // 修改表单的预验证
      editformrules: {
        attr_name: [
          {
            required: true,
            message: "请输入参数",
            trigger: "blur",
          },
        ],
      },
      // 修改提交所需的参数id
      attrid: 0,

    };
  },
  created() {
    this.getcatelist();
  },
  methods: {
    // 获取商品分类数据
    async getcatelist() {
      const res = await this.$http.get(uri.getcategories);
      if (res.meta.status === 200) {
        this.catelist = res.data;
        console.log(this.catelist);
      }
    },
    // 级联选择器发生变化时触发函数
    handleChange() {
      this.getParamsData();
    },
    // 获取参数的列表数据
    async getParamsData() {
      // console.log(this.selecdcateKeys);
      if (this.selecdcateKeys.length !== 3) {
        this.selecdcateKeys = [];
        this.manyTabdata=[]
        this.onlyTabdata=[]
      }
      const res = await this.$http.get(
        uri.getcategoriesidss + `/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      );
      console.log(res);
      if (res.meta.status === 200) {
        res.data.forEach((item) => {
          // 判断attr_vls为空就是一个空数组，不为空转化为数组
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
          // 单独提供自己的inputVisible和inputValue，来解决问题
          // 控制文本框的显示与隐藏
          item.inputVisible=false
          // 文本框中输入的值
          item.inputValue=''
        });
        // 判断数据是否是动态参数的数据
        if (this.activeName === "many") {
          this.manyTabdata = res.data;
        } else {
          this.onlyTabdata = res.data;
        }
      }
    },
    // tabs的点击事件
    slesecatehandleClick() {
      this.getParamsData();
      // console.log(this.activeName)
    },
    // 添加对话框关闭时刷新其中内容
    addDialogClosed() {
      this.$refs.addformref.resetFields();
    },
    // 添加对话框的提交
    addparams() {
      this.$refs.addformref.validate(async (valid) => {
        if (valid) {
          const res = await this.$http.post(
            uri.postcategoriesid + `/${this.cateId}/attributes`,
            {
              attr_name: this.addform.attr_name,
              attr_sel: this.activeName,
            }
          );
          // console.log(res);
          if (res.meta.status === 201) {
            this.$message.success(res.meta.msg);
            this.getParamsData();
          } else {
            this.$message.error(res.meta.msg);
          }
          this.addterdialogVisible = false;
        }
      });
    },
    // 修改按钮的点击事件
    async showEditDig(attr_id) {
      const res = await this.$http.get(
        uri.getcategriesattrId + `/${this.cateId}/attributes/${attr_id}`,
        { params: { attr_sel: this.activeName } }
      );
      console.log(res);
      this.editform = res.data;
      this.attrid = res.data.attr_id;
      this.editdialogVisible = true;
    },
    //修改对话框关闭时刷新其中的内容
    editDialogClosed() {
      this.$refs.editformref.resetFields();
    },
    //修改对话框的提交
    editparams() {
      this.$refs.editformref.validate(async (valid) => {
        if (valid) {
          const res = await this.$http.put(
            uri.putcategoriesattributes +
              `/${this.cateId}/attributes/${this.attrid}`,
            { attr_name: this.editform.attr_name, attr_sel: this.activeName }
          );
          console.log(res);
          if (res.meta.status === 200) {
            this.$message.success(res.meta.msg);
            this.getParamsData();
          } else {
            this.$message.error(res.meta.msg);
          }
        }
        this.editdialogVisible = false;
      });
    },
    // 删除按钮
    async showdelete(attrid) {
      const deleteconfrim = await this.$confirm(
        "将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (deleteconfrim === "confirm") {
        const res = await this.$http.delete(
          uri.deletecategoriesid + `/${this.cateId}/attributes/${attrid}`
        );
        // console.log(res)
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg);
          this.getParamsData();
        } else {
          this.$message.error(res.meta.msg);
        }
      } else {
        this.$message.info("已取消删除");
      }
    },
    // 文本框失去叫点或摁下了enter都会触发
    async handleInputConfirm(row){
      // 输入的内容不合法，失去焦点重置其中的内容并隐藏
      if(row.inputValue.trim().length===0){
        row.inputValue=''
        row.inputVisible=false
        return
      }
      // 把输入文本框的值push到attr_vals数组中，添加完成将文本框清空
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue=''
      row.inputVisible=false
      // 需要发起api请求，保存这次操作的数据
     const res= await this.$http.put(uri.putcategoriesattributes+`/${this.cateId}/attributes/${row.attr_id}`,{
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        attr_vals:row.attr_vals.join(" ")
      })
      if(res.meta.status===200){
        
      }else{
        this.$message.error("修改参数项失败")
      }
       
    },
    // 切换文本和按钮的，按钮事件,展示输入文本框
    showInput(row){
      row.inputVisible=true
      //让文本框自动获取焦点
      // nextTick的作用，当页面上元素被重新渲染之后，才会指定回调函数中的代码
       this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    // 删除tag标签事件,删除对应是参数可选项s
    handleClose(i,row){
      row.attr_vals.splice(i,1)
      this.saveAttrVals(row)

    },
    // 将对attr_vals的操作保存到数据库
   async saveAttrVals(row){
       const res= await this.$http.put(uri.putcategoriesattributes+`/${this.cateId}/attributes/${row.attr_id}`,{
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        attr_vals:row.attr_vals.join(" ")
      })
      if(res.meta.status===200){
        
      }else{
        this.$message.error("修改参数项失败")
      }
    }
  },

  computed: {
    // 判断是否是三级分类，如果不是三级分类就是true，是就是false
    isberverid() {
      if (this.selecdcateKeys.length !== 3) {
        return true;
      } else {
        return false;
      }
    },
    // 判断是否是三级分类，是就把其中的最后的三级分类id取出
    cateId() {
      if (this.selecdcateKeys.length === 3) {
        return this.selecdcateKeys[2];
      }
    },
  },
};
</script>

<style lang="less" scoped>
.avt_out {
  margin: 15px 0;
}
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 5px;
}
.input-new-tag{
  width: 120px;
}

</style>
